package com.hd.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author chentl
 * @version 文件上传工具
 * @Project 交通运输第三方监测平台
 * @Title FileUploadKit.java
 * @Description *
 * @Package com.hd.common.utils
 * @date 2021/1/14 5:36 下午
 * @Copyright: 深圳市宏电技术股份有限公司 All rights reserved.
 */
@Slf4j
public class FileUploadUtils {

    /**
     * 文件上传
     * @param filePath
     * @param fileName
     * @param stream
     * @return
     */
    public static String uploadFile(String filePath, String fileName, InputStream stream){
        String fileUrl = "";
        // 获取jvm系统属性值：user.dir用户的当前工作目录
        String dirPath = System.getProperty("user.dir");
        try {
            File dirFile = new File(new File(dirPath, "upload-file").toString(), filePath);
            if (!(dirFile.exists() && dirFile.isDirectory())){
                // 不存在则创建目录
                dirFile.mkdirs();
            }
            File file = new File(dirFile.toString(), fileName);
            if (!file.exists()){
                FileOutputStream fileOutputStream = new FileOutputStream(file.toString());
                byte[] buffer = new byte[1024 * 1024];
                int byteRead = 0;
                while ((byteRead = stream.read(buffer)) != -1){
                    fileOutputStream.write(buffer, 0, byteRead);
                    fileOutputStream.flush();
                }
                fileOutputStream.close();
                fileUrl = file.toString();
            }
        } catch (Exception e){
            log.error("文件上传出现异常：{}", e.getMessage());
        }
        return fileUrl;
    }


}
